package com.authentication.center.service;

import com.authentication.center.util.RedisCache;
import com.linzf.common.util.RtnMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 类描述：实现鉴权的service
 * @author linzf
 */
@Service
public class AuthService {

    @Autowired
    private RedisCache redisCache;

    @Value("${open.auth}")
    private String openAuth;

    /**
     * 功能描述：判断当前响应的url是否是在放行的目录中
     * @param auth
     * @return
     */
    public RtnMsg authUrl(Map<String,String> auth){
        String authUrl = auth.get("authUrl");
        String [] openAuths = openAuth.split(":");
        for(String s:openAuths){
            if(s.equals(authUrl)){
                return new RtnMsg(200,"验证通过！",null);
            }
        }
        // 当前的响应地址并不在放行的地址中，则需要验证token信息
        String token = auth.get("token");
        if(token==null|| "".equals(token)){
            return new RtnMsg(300,"当前用户未登录，请重新登录以后再继续操作！",null);
        }
        Map<String,Object> user = redisCache.getObject(token, Map.class);
        if(user==null){
            String refreshToken = redisCache.getString(token+"refresh");
            if(refreshToken==null || refreshToken.equals("")){
                return new RtnMsg(300,"当前用户未登录，请重新登录以后再继续操作！",null);
            }
            user = redisCache.getObject(refreshToken, Map.class);
            if(user==null){
                return new RtnMsg(300,"当前用户未登录，请重新登录以后再继续操作！",null);
            }
            redisCache.setObject(token,user,3600);
            redisCache.setObject(token+"refresh",refreshToken,7200);
            redisCache.setObject(refreshToken,user,7200);
        }
        String [] treeInfos = user.get("treeInfo").toString().split(":");
        for(String s:treeInfos){
            if(s.equals(authUrl)){
                return new RtnMsg(200,"验证通过！",null);
            }
        }
        return new RtnMsg(200,"验证通过！",null);
    }





}
